﻿using Examination.Args;
using Examination.Filter;
using Examination.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Examination.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [TypeFilter(typeof(WebVerificationFilterAttribute))]
    public class RankController : ControllerBase
    {
        private readonly DataContext _dataContext;

        public RankController(DataContext dataContext) => _dataContext = dataContext;

        [HttpPost]
        public async Task<IActionResult> Rank([FromQuery] int exam)
        {
            Model.Examination examination = await _dataContext.Examinations.FirstOrDefaultAsync(e => e.Id == exam);
            if (examination == null)
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = "比赛不存在" });
            }

            var ps = await _dataContext.Papers.Where(p => p.ExaminationId == exam && p.EndTime == new DateTime()).ToListAsync();
            bool flag = false;
            for (int i = 0; i < ps.Count; i++)
            {
                if ((DateTime.Now - ps[i].StartTime).TotalMinutes >= examination.Time || DateTime.Now > examination.EndTime)
                {
                    ps[i].EndTime = DateTime.Now;
                    _dataContext.Papers.Update(ps[i]);
                    flag = true;
                }
            }
            if (flag)
            {
                await _dataContext.SaveChangesAsync();
            }


            var papers = await _dataContext.Papers.Where(p => p.ExaminationId == exam && p.EndTime != new DateTime()).Join(_dataContext.Users, p => p.UserId, u => u.Id, (p, u) => new { p.Id, p.StartTime, p.EndTime, p.Score, user = u.Name, u.Number, u.Class }).ToListAsync();
            var userCount = await _dataContext.Users.CountAsync();
            return new JsonResult(new ResponseData() { Data = new { exam = examination, papers, userCount } });
        }
    }
}
